#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

#define SERVERPORT    8888
#define MAXDATASIZE 100

int sockfd,newfd;
void *read_socket();
void *write_socket();

int main(int argc ,char *argv[])
{
    int ret;
    pthread_t read_tid,write_tid;
    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(SERVERPORT);
    server_addr.sin_addr.s_addr=inet_addr(argv[1]);
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    if (sockfd<0)
    {
        printf("调用socket函数建立socket描述符出错！\n");
        exit(1);
    }
    printf("调用socket函数建立socket描述符成功！\n");
    bzero(&(server_addr.sin_zero),8);
    ret=connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
    if (ret<0)
    {
        printf("调用connect函数失败，客户端连接服务器失败!\n ");
        exit(2);
    }
    printf("调用connect函数成功，客户端连接服务器成功！\n");
    
    /************* 客户端建立两个线程，分别负责从socket读取和发送数据 **************/
    pthread_create(&read_tid,NULL,read_socket,NULL);
    pthread_create(&write_tid,NULL,write_socket,NULL);
    
    while(1)
    {
        sleep(10000);
    }
}
/****************** 从socket读取数据 ********************/
void *read_socket()
{
    int recv_num=0;
    char recv_buf[40];
    while (1)
    {
        recv_num=recv(sockfd,recv_buf,26,0);
        if (recv_num<0)
            printf("客户端：调用recv接收失败！\n");
        else
        {
            printf("客户端：调用recv函数成功，本次接收到%d个字节，内容为：\"%s\"\n",recv_num,recv_buf);
        }
        sleep(1);
    }
}

/****************** 向socket发送数据 ********************/
void *write_socket()
{
    int send_num=0;
    char send_buf[40]={9};
    while(1)
    {
        fgets(send_buf,40,stdin);
        send_num=send(sockfd,send_buf,1,0);
        if (send_num<0)
            printf("客户端：调用send函数失败！");
        else
        {
            printf("客户端：调用send函数成功，本次发送%d个字节，内容为：\"%s\"。\n",send_num,send_buf);
        }
        sleep(2);
    }
}
